<template>
  <div id="login">
    <div class="form">
      <h1>登录</h1>
      <form @submit.prevent="tologin">
        <el-input
          placeholder="请输入用户名"
          v-model="username"
          clearable
        ></el-input>
        <br />
        <el-input
          placeholder="请输入密码"
          v-model="password"
          show-password
          clearable
        ></el-input>
        <br />
        <el-button type="primary" size="medium" round @click="tologin"
          >登录</el-button
        >
        <br />
        <el-button type="text" size="small">忘记密码?</el-button>
        <el-button type="text" size="small" @click="tosign">注册</el-button>
      </form>
    </div>
  </div>
</template>

<script>
import { mapActions } from 'vuex';

export default {
  name: "loginList",
  data() {
    return {
      username: "",
      password: "",
    };
  },
  methods: {
    ...mapActions(['login', 'updateToken', 'updateRefreshToken']),
    async tologin() {
      try {
        const res = await this.login({
          username: this.username,
          password: this.password
        });
        if (res.code === 200) {
          this.updateToken(res.accessToken);
          this.updateRefreshToken(res.refreshToken);
          this.$message.success("登录成功");
          localStorage.setItem("username", this.username);
          this.$router.push('/'); // 导航到首页或其他页面
        } else {
          this.$message.error(res.message || "登录失败");
        }
      } catch (error) {
        this.$message.error(error.response?.data?.message || error.message || "网络错误");
      }
    },
    tosign() {
      this.$router.push("/signIn");
    },
  },
};
</script>

<style>
body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  height: 100vh;
}

.form {
  width: 400px;
  margin: 200px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.form h1 {
  text-align: center;
  margin-bottom: 20px;
}

.form form {
  display: flex;
  flex-direction: column;
}

.form form input {
  margin-bottom: 20px;
}
</style>
